package com.ikingtech.framework.sdk.data.mybatisplus.helper;

import com.ikingtech.framework.sdk.data.mybatisplus.entity.SortEntity;
import com.ikingtech.framework.sdk.utils.Tools;

import java.util.Collections;
import java.util.List;

/**
 * @author tie yan
 */
public class OneLevelDragHelper<T extends SortEntity> extends AbstractDragHelper<T>{

    @Override
    public List<T> drag() {
        T currentNode = this.currentNode.get();
        T targetNode = this.targetNode.get();
        boolean isUp = currentNode.getSortOrder() > targetNode.getSortOrder();
        int startNodeOrder;
        int endNodeOrder;
        int currentNodeOrder;
        if (currentNode.getSortOrder() > targetNode.getSortOrder()) {
            startNodeOrder = Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() - 1 : targetNode.getSortOrder();
            endNodeOrder = currentNode.getSortOrder();
            currentNodeOrder = Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() : targetNode.getSortOrder() + 1;
        } else if (currentNode.getSortOrder() < targetNode.getSortOrder()) {
            startNodeOrder = currentNode.getSortOrder();
            endNodeOrder = Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() : targetNode.getSortOrder() + 1;
            currentNodeOrder = Boolean.TRUE.equals(this.beforeTarget) ? targetNode.getSortOrder() - 1 : targetNode.getSortOrder();
        } else {
            return Collections.emptyList();
        }
        List<T> nodeBetweenCurrentAndTarget = this.nodeBetweenCurrentAndTarget.apply(startNodeOrder, endNodeOrder);
        currentNode.setSortOrder(currentNodeOrder);
        List<T> sortedEntities = Tools.Coll.traverse(nodeBetweenCurrentAndTarget, entity -> {
            entity.setSortOrder(isUp ?
                    entity.getSortOrder() + 1 :
                    entity.getSortOrder() - 1);
            return entity;
        });
        sortedEntities.add(currentNode);
        return sortedEntities;
    }
}
